#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <assert.h>
#include <string.h>
#define NUM 1024
#define OPT_NUM 64
char LineCommand[NUM];
char* myargv[OPT_NUM];
int lastCode = 0;
int lastSig = 0;

int main()
{
    while(1)
    {
        //打印输出提示符
        printf("用户名@主机名 当前路径# ");
        fflush(stdout);//刷新缓冲区！

        //获取用户输入，我们输入的时候会自己输入\n
        char* s = fgets(LineCommand,sizeof(LineCommand)-1,stdin);
        (void)s;
        assert (s != NULL);
        LineCommand[strlen(LineCommand)-1] = 0;//这是为了清楚最后一个\n!

        //"ls -a -l" -> "ls" "-a" "-l" 切割字串！
        myargv[0] = strtok(LineCommand," ");
        int i = 1;
        if(myargv[0] != NULL && strcmp(myargv[0],"ls")==0)
        {
            myargv[i++] = (char*)"--color=auto";
        }
        //strtok遇到空的返回值为NULL 同时要myargv要以NULL结尾！
        //while(myargv[i++] = strtok(NULL," "));
        //如果是cd 指令就不需要创建子进程，让shell自己执行对应的命令！，本质就是调用系统接口！
        if(myargv[0] != NULL  && strcmp(myargv[0],"cd")==0)
        {
            if(myargv[1] != NULL)
            {
                chdir(myargv[1]);
            }
            continue;
        }
        //获取进程结束的结果
        if(myargv[0] != NULL && myargv[1] != NULL && strcmp(myargv[0],"echo")==0 )
        {
            if(strcmp(myargv[1],"$?")==0)
            {
                printf("%d,%d\n",lastCode,lastSig);
            }
            else 
            {
                printf("%s\n",myargv[1]);
            }
            continue;
        }
#ifdef DEBUG 
        for(int i = 0;myargv[i];i++)
        {
            printf("myargv[%d]:%s\n",i,myargv[i]);
        }
#endif
        //执行命令！——让子进程执行！
        pid_t id = fork();
        assert(id != -1);
        if(id == 0)
        {
            execvp(myargv[0],myargv);
            exit(1);
        }
        int status = 0;
        pid_t ret =  waitpid(id,&status,0);
        (void)ret;
        assert(ret > 0);
        lastCode = ((status>>8)&0xFF);
        lastSig = status& 0x7F;
    }
    return 0;
}
